<template>
  <a-drawer
    :title="title"
    :width="720"
    :visible="visible"
    :wrapStyle="{height: '100%',overflow: 'auto',paddingBottom: '108px'}"
    @close="close"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item label="菜单类型" :labelCol="labelCol" :wrapperCol="wrapperCol" >
          <a-radio-group :disabled="model.id ? true : false" @change="onChangeMenuType" v-model="localMenuType">
            <a-radio :value="0">一级菜单</a-radio>
            <a-radio :value="1">子菜单</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="菜单名称"
          hasFeedback >
          <a-input placeholder="请输入菜单名称" v-decorator="[ 'menuName', {rules: [{ required: true, message: '请输入菜单标题!' }]}]"/>
        </a-form-item>

        <a-form-item
          v-if="localMenuType!==0"
          label="上级菜单"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :validate-status="validateStatus"
          :hasFeedback="true"
          :required="true">
          <span slot="help">{{ validateStatus === 'error'?'请选择上级菜单':'&nbsp;&nbsp;' }}</span>
          <tree-select
            style="width:100%"
            :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }"
            :treeData="treeData"
            v-decorator="['parentId', {}]"
            placeholder="请选择父级菜单"
            @change="handleParentIdChange">
          </tree-select>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="菜单图标">
          <a-input placeholder="点击右侧按钮选择图标" v-decorator="['icon']">
            <a-icon slot="addonAfter" type="setting" @click="selectIcons" />
          </a-input>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="菜单路径">
          <a-input placeholder="请输入菜单路径" v-decorator="[ 'url',{rules: [{ required: true, message: '请输入菜单路径!' }]}]"/>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="组件">
          <a-input placeholder="请输入前端组件" v-decorator="[ 'componentName',{rules: [{ required: true, message: '请输入前端组件!' }]}]"/>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="授权标识">
          <a-input placeholder="多个用逗号分隔, 如: user:list,user:create" v-decorator="[ 'permissions', {}]"/>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="排序">
          <a-input-number placeholder="请输入菜单排序" style="width: 200px" v-decorator="[ 'orderNum',{initialValue:1.0}]"/>
        </a-form-item>

      </a-form>
    </a-spin>

    <div class="drawer-bottom-button">
      <a-button :style="{marginRight: '8px'}" @click="close">取消</a-button>
      <a-button @click="handleSubmit" type="primary">保存</a-button>
    </div>

    <!-- 选择图标 -->
    <icons @choose="handleIconChoose" @close="handleIconCancel" :iconChooseVisible="iconChooseVisible"></icons>
  </a-drawer>
</template>

<script>
import { apiQueryPermissionList, apiSavePermission } from '@/api/system'
import { TreeSelect } from 'ant-design-vue'
import pick from 'lodash.pick'
import DictSelectTag from '@/components/dict/DictSelectTag'
import Icons from './icon/Icons'

export default {
  name: 'PermissionModal',
  components: {
    TreeSelect, DictSelectTag, Icons
  },
  data () {
    return {
      title: '',
      visible: false,
      iconChooseVisible: false,
      confirmLoading: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      localMenuType: 0,
      form: this.$form.createForm(this),
      treeData: [],
      validateStatus: '',
      model: {}
    }
  },
  methods: {
    show (title, record) {
      this.form.resetFields()
      this.validateStatus = ''
      this.localMenuType = 0
      this.model = {}
      this.visible = true
      this.title = title
      if (record) {
        this.model = Object.assign({}, record)
        this.localMenuType = record.parentId === null || record.parentId === '' ? 0 : 1
        this.initFormValue(record)
      }
      this.loadTree()
    },
    initFormValue () {
      console.log(this.model)
      let fieldsVal = {}
      fieldsVal = pick(this.model, 'parentId', 'menuName', 'url', 'componentName', 'icon', 'permissions', 'orderNum')
      this.$nextTick(() => {
        this.form.setFieldsValue(fieldsVal)
      })
    },
    close () {
      this.visible = false
    },
    loadTree () {
      const that = this
      apiQueryPermissionList().then((res) => {
        if (res.code === 1) {
          that.treeData = that.getTreeData(res.data)
        }
      })
    },
    getTreeData (list) {
      const treeData = []
      for (let i = 0; i < list.length; i++) {
        const temp = {
          title: list[i].menuName,
          value: list[i].id,
          key: list[i].id
        }
        if (list[i].children !== null && list[i].children.length > 0) {
          temp.children = [...this.getTreeData(list[i].children)]
        }
        treeData.push(temp)
      }
      return treeData
    },
    onChangeMenuType (e) {
      this.localMenuType = e.target.value
    },
    handleParentIdChange (value) {
      if (!value) {
        this.validateStatus = 'error'
      } else {
        this.validateStatus = 'success'
      }
    },
    selectIcons () {
      this.iconChooseVisible = true
    },
    handleIconCancel () {
      this.iconChooseVisible = false
    },
    handleIconChoose (value) {
      this.form.setFieldsValue({ icon: value })
      this.iconChooseVisible = false
    },
    handleSubmit () {
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log(values)
          const formData = Object.assign(this.model, values)
          formData.parentId = this.localMenuType === 0 ? '' : formData.parentId
          delete formData.children
          this.confirmLoading = true
          console.log(formData)
          apiSavePermission(formData).then((res) => {
            if (res.code === 1) {
              this.$message.success(res.msg)
              this.$emit('ok')
              this.close()
            } else {
              this.$message.warning(res.msg)
            }
          }).finally(() => {
            this.confirmLoading = false
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.drawer-bottom-button {
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e9e9e9;
  padding: 10px 16px;
  background: #fff;
  text-align: right;
}

</style>
